package com.example.motion.controller;

import com.example.motion.config.ResultT;
import com.example.motion.config.WechatApiUtils;
import com.example.motion.model.User;
import com.example.motion.model.request.LoginRequest;
import com.example.motion.model.request.RegisterRequest;
import com.example.motion.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 登录
 *
 * @author jxf
 * @version 1.0.0
 * @since 1.0.0
 */
@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultT login(@Validated @RequestBody LoginRequest loginRequest) {

        User user = userService.findUserByOpenid(loginRequest.getOpenid());
        if (user != null) {
            return ResultT.ok(user);
        }
        return ResultT.error(201, "openid不存在");
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResultT register(@Validated @RequestBody RegisterRequest registerRequest) {
        User user = userService.findUserByPoliceInfo(registerRequest.getName(), registerRequest.getOfficeCode());
        if (user != null) {
            user.setOpenid(registerRequest.getOpenid());
            user.setAvatar(registerRequest.getAvatar());
            userService.updateOpenid(user);
            return ResultT.ok(user);
        }
        return ResultT.error(201, "用户不存在");
    }

    @RequestMapping(value = "/getopenid")
    @ResponseBody
    public String getOpenid(String code) {
        System.out.println(code);
        String result = WechatApiUtils.jscode2session(code);
        return result;
    }


}
